package io.github.zeleven.mua.fraction;

import io.github.zeleven.mua.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.webengine.ResourceRequest;
import ohos.agp.components.webengine.ResourceResponse;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import ohos.agp.utils.TextTool;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;

/**
 * HelpFraction
 *
 * @since 2021-05-11
 */
public class HelpFraction extends AbilitySlice {
    private static final int INT = 0x001234;
    private WebView mWebView;
    private HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP, INT, "mua");

    /**
     * HelpFraction
     *
     */
    public HelpFraction() {
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_fragment_help);
        Image back = (Image) findComponentById(ResourceTable.Id_ig_ic_back);
        back.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onBackPressed();
            }
        });
        mWebView = (WebView) findComponentById(ResourceTable.Id_docs_webview);
        mWebView.getWebConfig().setJavaScriptPermit(true);
        mWebView.setWebAgent(new WebAgent() {
            @Override
            public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
                final String authority = "example.com";
                final String rawFile = "/rawfile/";
                final String local = "/local/";
                Uri requestUri = request.getRequestUrl();
                if (authority.equals(requestUri.getDecodedAuthority())) {
                    String path = requestUri.getDecodedPath();
                    if (TextTool.isNullOrEmpty(path)) {
                        return super.processResourceRequest(webView, request);
                    }
                    if (path.startsWith(rawFile)) {
                        // 根据自定义规则访问资源文件
                        String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                        String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                        try {
                            Resource resource = HelpFraction.this.getResourceManager().getRawFileEntry(rawFilePath)
                                    .openRawFile();
                            ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                            return response;
                        } catch (IOException e) {
                            HiLog.info(hiLogLabel, "open raw file failed");
                        }
                    }
                    if (path.startsWith(local)) {
                        // 根据自定义规则访问本地文件
                        String localFile = getContext().getFilesDir() + path.replace(local, "/");
                        HiLog.info(hiLogLabel, "open local file " + localFile);
                        File file = new File(localFile);
                        if (!file.exists()) {
                            HiLog.info(hiLogLabel, "file not exists");
                            return super.processResourceRequest(webView, request);
                        }
                        String mimeType = URLConnection.guessContentTypeFromName(localFile);
                        try {
                            InputStream inputStream = new FileInputStream(file);
                            ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
                            return response;
                        } catch (IOException e) {
                            HiLog.info(hiLogLabel, "open local file failed");
                        }
                    }
                }
                return super.processResourceRequest(webView, request);
            }
        });
        mWebView.load("https://example.com/rawfile/markdown-cheatsheet-zh.html");
    }
}